<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/15 0015
 * Time: 16:33
 */

namespace Admin\Model;


use Think\Model;

class CategoryModel extends Model
{

    // 添加时调用create方法允许介接受的字段
    protected $insertFields = 'cat_name,parent_id';

    protected $updateFields = 'id,cat_name,parent_id';
    //定义规则
    protected $_validate = array(
        array('cat_name', 'require', '分类名称不能为空', 1),
    );

    //找一个分类的子分类
    public function getChildren($catId)
    {
        //取出所有的分类
        $data = $this->select();
        //查找子分类
        return $this->_getChildren($data, $catId, true);

    }

    private function _getChildren($data, $catId, $isClear = false)
    {
        static $res = array();
        if ($isClear) {
            $res = array();
        }
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $catId) {
                $res[] = $v['id'];
                //在查找$v的子类
                $this->_getChildren($data, $v['id']);
            }

        }
        return $res;
    }

//获取树形结构
    public function getTree()
    {
        $data = $this->select();
        return $this->_getTree($data);
    }

    private function _getTree($data, $parent_id = 0, $level = 0)
    {
        static $res = array();
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                $v['level'] = $level;
                $res[] = $v;
                $this->_getTree($data, $v['id'], $level + 1);
            }
        }
        return $res;
    }
}